package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.Mapper.DishMapper;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    //①. 保存菜品基本信息 ;
    //
    //②. 获取保存的菜品ID ;
    //
    //③. 获取菜品口味列表，遍历列表，为菜品口味对象属性dishId赋值;
    //
    //④. 批量保存菜品口味列表;
    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional //涉及多张表的操作,事务控制
    public void saveWithFlavor(DishDto dishDto) {
        this.save(dishDto);
        //获得菜品id
        Long id = dishDto.getId();
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询基本信息dish
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(dish, dishDto);
        //查询口味信息dishflavor
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        //条件id查对应的口味
        qw.eq(DishFlavor::getId, dish.getId());
        //查出来之后将基本属性拷贝到dto对象里,口味信息也set进dto对象,返回这个对象
        List<DishFlavor> flavors = dishFlavorService.list(qw);
        dishDto.setFlavors(flavors);

        DishFlavor byId = dishFlavorService.getById(dish);

        return dishDto;
    }

    @Override
    public void UpdateWithFlavor(DishDto dishDto) {
        //更新dish基本信息
        this.updateById(dishDto);
        //清理数据
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getId, dishDto.getId());
        dishFlavorService.remove(qw);
        //拿到口味数据,其中只是封装了name(口味名称 ),和value(口味list) 没有id,遍历口味数据,将其中的每一项重新set一个id
        // 这个id从dto对象中获取

        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((it) -> {
            it.setDishId(dishDto.getId());
            return it;
        }).collect(Collectors.toList());


        dishFlavorService.saveBatch(flavors);


    }


}
